from django.shortcuts import render
from django.http import JsonResponse
from django.views import View
from apps.oauth.models import OAuthQQUser
from apps.users.models import User
from django.conf import settings
from QQLoginTool.QQtool import OAuthQQ
from .utils import dumps_id_way, loads_id_way
from django.contrib.auth import login
import json
import re
# Create your views here.

# 拿到QQ的扫码页面
class QQUrlView(View):
    def get(self, request):
        # 拿到数据
        next = request.GET.get('next')

        # 生成qq请求对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)

        # 拿到QQ扫码登录页面
        login_url = oauth.get_qq_url()

        # 返回给前端
        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'login_url': login_url})


# 使用扫码得到的code拿到takon和openid

class QQUserView(View):
    def post(self, request):
        ''' 用户openid绑定用户'''
        # 拿到数据
        data_dict = json.loads(request.body.decode())
        print(data_dict)
        mobile = data_dict.get('mobile')
        password = data_dict.get('password')
        sms_code_client = data_dict.get('sms_code')
        openid_d = data_dict.get('access_token')
        openid = loads_id_way(openid_d)
        # 效验数据
        if not all([mobile, password, sms_code_client, openid]):
            return JsonResponse({'code': 400,
                                 'errmsg': '数据不全'})

            # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                'errmsg': '请输入正确的手机号码'})

            # 判断密码是否合格
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return JsonResponse({'code': 400,
                                'errmsg': '请输入8-20位的密码'})
        # 绑定用户判断用户是否以存在
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 不存在就创建一个用户
            user = User.objects.create_user(username=mobile,
                                            password=password,
                                            mobile=mobile)
        else:
            # 用户存在先检查密码
            if not user.check_password(password):
                return JsonResponse({'code': 400,
                                'errmsg': '密码错误'})


        # 将用户与openid绑定
        try:
            OAuthQQUser.objects.create(user=user,
                                       openid=openid)
        except OAuthQQUser.DoesNotExist:
            return JsonResponse({'code': 400,
                                'errmsg': 'openid绑定错误'})

        # 绑定成功设置session
        login(request, user)

        response = JsonResponse({'code': 0,
                                 'errmsg': 'ok'})
        response.set_cookie('username', user.username, max_age=300)

        return response




        # 设置session

        # 返回数据


    def get(self, request):
        '''判断openid'''
        # 拿到code
        code = request.GET.get('code')
        if not code:
            return JsonResponse({'code': 400,
                                 'errmsg': '无参数'})

        # 生成QQ请求对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        )

        try:
            # 使用对象拿到takon
            takon = oauth.get_access_token(code)

            # 拿到openid
            openid = oauth.get_open_id(takon)

        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': 'oauth2.0认证失败, 即获取qq信息失败'})

        # 判断用户是否绑定如果绑定就返回页面没有绑定就返回openid进入绑定页面
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # openid没有绑定用户把openid加密返回给前端
            access_token = dumps_id_way(openid)

            return JsonResponse({'code': 200,
                                 'errmsg': '用户未绑定',
                                 'access_token': access_token})

        else:
            # openid绑定用户状态保持设置session
            login(request, qq_user.user)

            response = JsonResponse({'code': 0,
                                     'errmsg': 'ok'})
            response.set_cookie('username', qq_user.user.username, max_age=300)

            return response

